using System;
using System.Collections.Generic;
using System.Text;

namespace ClientTools.Library.Media
{
    public class MediaManager
    {
        public MediaCollection GetRootMedias(bool recursive) 
        {
            MediaCollection returnValue = new MediaCollection();
            foreach (umbraco.cms.businesslogic.media.Media umbracoMedia in umbraco.cms.businesslogic.media.Media.GetRootMedias())
	        {
                Media newMedia = this.CreateNewMediaFromUmbracoMedia(umbracoMedia);
                returnValue.Add(newMedia);
                if (recursive) 
                {
                    newMedia.Children = this.GetMediasFromNode(umbracoMedia, true);
                }
	        }
            return returnValue;
        }

        public MediaCollection GetMediaNode(int mediaId, bool recursive)
        {
            umbraco.cms.businesslogic.media.Media umbracoMedia = new umbraco.cms.businesslogic.media.Media(mediaId);
            MediaCollection returnValue = new MediaCollection();
            returnValue.Add(this.CreateNewMediaFromUmbracoMedia(umbracoMedia));
            if (recursive)
            {
                returnValue[0].Children = this.GetMediasFromNode(umbracoMedia, true);
            }
            return returnValue;
        }

        public MediaCollection GetMediasFromNode(int mediaId, bool recursive)
        {
            umbraco.cms.businesslogic.media.Media umbracoMedia = new umbraco.cms.businesslogic.media.Media(mediaId);
            return this.GetMediasFromNode(umbracoMedia, recursive);
        }

        public MediaCollection GetMediasFromNode(umbraco.cms.businesslogic.media.Media umbracoMedia, bool recursive)
        {
            MediaCollection returnValue = new MediaCollection();
            foreach (umbraco.cms.businesslogic.media.Media umbracoChildMedia in umbracoMedia.Children)
            {
                Media newMedia = this.CreateNewMediaFromUmbracoMedia(umbracoChildMedia); 
                returnValue.Add(newMedia);
                if (recursive) 
                {
                    newMedia.Children = this.GetMediasFromNode(umbracoChildMedia, true);
                }
            }
            return returnValue;
        }

        private Media CreateNewMediaFromUmbracoMedia(umbraco.cms.businesslogic.media.Media umbracoMedia)
        {
            Media returnValue = new Media(umbracoMedia);

            foreach (umbraco.cms.businesslogic.property.Property umbracoProperty in umbracoMedia.getProperties)
            {
                Property newProperty = new Property(umbracoProperty);
                returnValue.Properties.Add(newProperty);
            }

            return returnValue;
        }

        private umbraco.cms.businesslogic.property.Property GetFilePropertyFromMedia(umbraco.cms.businesslogic.media.Media media)
        {
            foreach (umbraco.cms.businesslogic.property.Property umbracoProperty in media.GenericProperties)
            {
                if (umbracoProperty.PropertyType.DataTypeDefinition.UniqueId == new Guid("5032a6e6-69e3-491d-bb28-cd31cd11086c")) ;
                {
                    return umbracoProperty;
                }
            }
            return null;
        }

        public bool DeleteMedia(int mediaId)
        {
            umbraco.cms.businesslogic.media.Media media = new umbraco.cms.businesslogic.media.Media(mediaId);
            umbraco.cms.businesslogic.property.Property fileProperty = this.GetFilePropertyFromMedia(media);
            if (fileProperty != null)
            {
                this.DeleteMediaFiles(fileProperty.Id);
            }
            media.delete();
            umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, 0, "ClientTools4Umbraco: Deleted media '" + mediaId.ToString() + "'");
            return true;
        }

        private bool DeleteMediaFiles(int propertyId)
        {
            string mediaPath = System.IO.Path.Combine(umbraco.GlobalSettings.FullpathToRoot, "media/" + propertyId.ToString());
            if (System.IO.Directory.Exists(mediaPath))
            {
                foreach (string file in System.IO.Directory.GetFiles(mediaPath))
                {
                    System.IO.File.Delete(file);
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, 0, "ClientTools4Umbraco: Deleted file '" + System.IO.Path.GetFileName(file) + "' for media '" + propertyId.ToString() + "'");
                }
                System.IO.Directory.Delete(mediaPath);
            }
            return true;
        }

        public Media CreateNewImage(umbraco.BusinessLogic.User user, int parentMediaId, string imageName, byte[] content)
        {
            umbraco.cms.businesslogic.media.Media parentMedia = new umbraco.cms.businesslogic.media.Media(parentMediaId);

            umbraco.cms.businesslogic.media.MediaType imageMediaType = umbraco.cms.businesslogic.media.MediaType.GetByAlias("Image");
            umbraco.cms.businesslogic.media.Media newImage = umbraco.cms.businesslogic.media.Media.MakeNew(imageName, imageMediaType, user, parentMediaId);

            umbraco.cms.businesslogic.property.Property propertyUmbracoFile = newImage.getProperty("umbracoFile");
            string mediaPath = System.IO.Path.Combine(umbraco.GlobalSettings.FullpathToRoot, System.IO.Path.Combine("media" , propertyUmbracoFile.Id.ToString()));
            string fullFilePath = System.IO.Path.Combine(mediaPath, imageName);

            if (!System.IO.Directory.Exists(mediaPath)) 
            {
                System.IO.Directory.CreateDirectory(mediaPath);
            }
            System.IO.File.WriteAllBytes(fullFilePath, content);
            propertyUmbracoFile.Value = "/media/" + propertyUmbracoFile.Id.ToString() + "/" + imageName;

            string ext = System.IO.Path.GetExtension(imageName).Substring(1);
            newImage.getProperty("umbracoExtension").Value = ext;

            System.IO.FileInfo fi = new System.IO.FileInfo(fullFilePath);
            newImage.getProperty("umbracoBytes").Value = fi.Length.ToString();

            if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + ext.ToLower() + ",") > 0)
            {
                int fileWidth;
                int fileHeight;

                System.IO.FileStream fs = new System.IO.FileStream(fullFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

                using (System.Drawing.Image image = System.Drawing.Image.FromStream(fs))
                {
                    fileWidth = image.Width;
                    fileHeight = image.Height;
                }
                fs.Close();
                //try
                //{
                newImage.getProperty("umbracoWidth").Value = fileWidth.ToString();
                newImage.getProperty("umbracoHeight").Value = fileHeight.ToString();
                //}
                //catch
                //{
                //    //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, u, m.Id, "Zeile 116");
                //}

                // Generate thumbnail
                float fx = fileWidth / 100;
                float fy = fileHeight / 100; // subsampling factors
                // must fit in thumbnail size
                float f = Math.Max(fx, fy); if (f < 1) f = 1;
                int widthTh = (int)(fileWidth / f); int heightTh = (int)(fileHeight / f);
                string fileNameThumb = fullFilePath.Replace("." + ext, "_thumb." + ext);
                using (System.Drawing.Image image = System.Drawing.Image.FromFile(fullFilePath))
                {

                    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image, widthTh, heightTh))
                    {
                        //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - Jetzt wird das Thumbnail 4 erstellt...");
                        //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - fullFilePath: " + fullFilePath);
                        //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - fileNameThumb: " + fileNameThumb);
                        //try
                        //{
                        bitmap.Save(fileNameThumb, System.Drawing.Imaging.ImageFormat.Jpeg);
                        //}
                        //catch //(Exception ex)
                        //{
                        //    //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - Jetzt wird das Thumbnail 5 erstellt - " + fileNameThumb+ " - ");
                        //}
                    }
                }
            }
            return this.CreateNewMediaFromUmbracoMedia(newImage);
        }

        public Media CreateNewFile(umbraco.BusinessLogic.User user, int parentMediaId, string fileName, byte[] content)
        {
            umbraco.cms.businesslogic.media.Media parentMedia = new umbraco.cms.businesslogic.media.Media(parentMediaId);

            umbraco.cms.businesslogic.media.MediaType imageMediaType = umbraco.cms.businesslogic.media.MediaType.GetByAlias("File");
            umbraco.cms.businesslogic.media.Media newFile = umbraco.cms.businesslogic.media.Media.MakeNew(fileName, imageMediaType, user, parentMediaId);

            umbraco.cms.businesslogic.property.Property propertyUmbracoFile = newFile.getProperty("umbracoFile");
            string mediaPath = System.IO.Path.Combine(umbraco.GlobalSettings.FullpathToRoot, System.IO.Path.Combine("media", propertyUmbracoFile.Id.ToString()));
            string fullFilePath = System.IO.Path.Combine(mediaPath, fileName);

            if (!System.IO.Directory.Exists(mediaPath))
            {
                System.IO.Directory.CreateDirectory(mediaPath);
            }
            System.IO.File.WriteAllBytes(fullFilePath, content);
            propertyUmbracoFile.Value = "/media/" + propertyUmbracoFile.Id.ToString() + "/" + fileName;

            string ext = System.IO.Path.GetExtension(fileName).Substring(1);
            newFile.getProperty("umbracoExtension").Value = ext;

            System.IO.FileInfo fi = new System.IO.FileInfo(fullFilePath);
            newFile.getProperty("umbracoBytes").Value = fi.Length.ToString();

            return this.CreateNewMediaFromUmbracoMedia(newFile);
        }

        public Media CreateNewFolder(umbraco.BusinessLogic.User user, int parentMediaId, string folderName)
        {
            umbraco.cms.businesslogic.media.Media parentMedia = new umbraco.cms.businesslogic.media.Media(parentMediaId);
            umbraco.cms.businesslogic.media.MediaType mediaType = umbraco.cms.businesslogic.media.MediaType.GetByAlias("Folder");

            umbraco.cms.businesslogic.media.Media newFolderMedia = umbraco.cms.businesslogic.media.Media.MakeNew(folderName, mediaType, user, parentMediaId);
            return this.CreateNewMediaFromUmbracoMedia(newFolderMedia);
        }
    }
}
